<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>英语单词听写工具</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        header {
            background: linear-gradient(90deg, #4b6cb7, #182848);
            color: white;
            padding: 25px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        h1 {
            font-size: 2.8em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        .subtitle {
            font-size: 1.2em;
            opacity: 0.9;
        }
        .main-content {
            display: flex;
            flex-wrap: wrap;
            min-height: 600px;
        }
        .upload-section {
            flex: 1;
            min-width: 300px;
            padding: 30px;
            background: #f0f4f8;
            border-right: 1px solid #d1dfff;
        }
        .dictation-section {
            flex: 2;
            min-width: 500px;
            padding: 30px;
            display: flex;
            flex-direction: column;
            background: #fafbff;
        }
        .section-title {
            font-size: 1.6em;
            margin-bottom: 20px;
            color: #2c3e50;
            padding-bottom: 12px;
            border-bottom: 3px solid #4b6cb7;
            position: relative;
        }
        .section-title:after {
            content: '';
            position: absolute;
            bottom: -3px;
            left: 0;
            width: 60px;
            height: 3px;
            background: #ff6b6b;
        }
        .upload-area {
            border: 3px dashed #4b6cb7;
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            margin-bottom: 25px;
            background: white;
            transition: all 0.3s;
            cursor: pointer;
            box-shadow: inset 0 0 10px rgba(75, 108, 183, 0.1);
        }
        .upload-area:hover {
            background: #e3f2fd;
            transform: translateY(-3px);
            box-shadow: inset 0 0 15px rgba(75, 108, 183, 0.2), 0 5px 15px rgba(0,0,0,0.1);
        }
        .upload-icon {
            font-size: 3.5em;
            color: #4b6cb7;
            margin-bottom: 15px;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }
        .file-inputs {
            margin: 20px 0;
        }
        .file-input {
            margin: 15px 0;
        }
        .file-input input[type="file"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 10px;
            margin: 8px 0;
            background: #fff;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
        }
        .file-input label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        /* Simplified button styles */
        .btn {
            background: linear-gradient(to bottom, #4b6cb7, #3a5795);
            color: white;
            border: none;
            padding: 14px 28px;
            border-radius: 50px;
            cursor: pointer;
            font-size: 1.1em;
            font-weight: 600;
            transition: all 0.3s;
            margin: 8px;
            box-shadow: 0 5px 15px rgba(75, 108, 183, 0.4);
            border: 2px solid #2a4a85;
        }
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(75, 108, 183, 0.6);
        }
        .btn:active {
            transform: translateY(1px);
            box-shadow: 0 3px 10px rgba(75, 108, 183, 0.4);
        }
        .btn-secondary {
            background: linear-gradient(to bottom, #6c757d, #5a6268);
            border: 2px solid #495057;
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.4);
        }
        .btn-success {
            background: linear-gradient(to bottom, #28a745, #218838);
            border: 2px solid #1e7e34;
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.4);
        }
        .btn-warning {
            background: linear-gradient(to bottom, #ffc107, #e0a800);
            color: #212529;
            border: 2px solid #d39e00;
            box-shadow: 0 5px 15px rgba(255, 193, 7, 0.4);
        }
        .btn-danger {
            background: linear-gradient(to bottom, #dc3545, #c82333);
            border: 2px solid #bd2130;
            box-shadow: 0 5px 15px rgba(220, 53, 69, 0.4);
        }
        .btn-info {
            background: linear-gradient(to bottom, #17a2b8, #138496);
            border: 2px solid #117a8b;
            box-shadow: 0 5px 15px rgba(23, 162, 184, 0.4);
        }
        .btn-lg {
            padding: 16px 35px;
            font-size: 1.2em;
        }
        .btn-sm {
            padding: 10px 20px;
            font-size: 0.95em;
        }
        .btn-block {
            display: block;
            width: 100%;
        }
        .word-display {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            margin: 25px 0;
            padding: 30px;
            background: #f8f9ff;
            border-radius: 20px;
            box-shadow: inset 0 0 15px rgba(75, 108, 183, 0.1), 0 5px 15px rgba(0,0,0,0.05);
            border: 2px solid #e1e8ff;
        }
        .word {
            font-size: 4.5em;
            font-weight: 800;
            color: #4b6cb7;
            margin-bottom: 25px;
            min-height: 1.3em;
            text-shadow: 3px 3px 6px rgba(0,0,0,0.1);
            font-family: 'Arial Rounded MT Bold', 'Arial', sans-serif;
        }
        .meaning {
            font-size: 2em;
            color: #666;
            min-height: 1.3em;
            font-weight: 500;
            padding: 15px 25px;
            background: rgba(255,255,255,0.7);
            border-radius: 15px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
        }
        .controls {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 20px;
            margin: 35px 0;
        }
        .control-btn {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            font-size: 2em;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 20px rgba(0,0,0,0.2);
            transition: all 0.2s;
            border: 3px solid white;
            background: linear-gradient(to bottom, #4b6cb7, #3a5795);
            color: white;
        }
        .control-btn:hover {
            transform: scale(1.08);
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        }
        .control-btn:active {
            transform: scale(0.95);
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
        }
        .progress-container {
            width: 100%;
            background: #e9ecef;
            border-radius: 15px;
            height: 25px;
            margin: 25px 0;
            overflow: hidden;
            box-shadow: inset 0 2px 5px rgba(0,0,0,0.1);
        }
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #4b6cb7, #182848);
            border-radius: 15px;
            transition: width 0.4s ease;
            box-shadow: 0 0 10px rgba(75, 108, 183, 0.5);
        }
        .progress-text {
            text-align: center;
            font-weight: bold;
            margin-top: 12px;
            font-size: 1.1em;
            color: #2c3e50;
        }
        .settings-section {
            flex: 1;
            min-width: 300px;
            padding: 30px;
            background: #f0f4f8;
            border-left: 1px solid #d1dfff;
        }
        .setting-group {
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e1e8ff;
        }
        .setting-group h3 {
            margin-top: 0;
            color: #2c3e50;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }
        .setting-item {
            margin: 18px 0;
        }
        .setting-item label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        .setting-item input, .setting-item select {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 10px;
            background: #fff;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
            transition: border-color 0.3s;
        }
        .setting-item input:focus, .setting-item select:focus {
            border-color: #4b6cb7;
            box-shadow: 0 0 8px rgba(75, 108, 183, 0.3);
        }
        .setting-item input[type="range"] {
            padding: 0;
        }
        .setting-item input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            cursor: pointer;
        }
        .mode-toggle {
            display: flex;
            margin: 25px 0;
            background: #e9ecef;
            border-radius: 30px;
            overflow: hidden;
            box-shadow: inset 0 2px 5px rgba(0,0,0,0.1);
        }
        .mode-btn {
            flex: 1;
            padding: 18px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
            font-size: 1.1em;
        }
        .mode-btn:hover {
            background-color: #d1d1d1;
        }
        .mode-btn.active {
            background: linear-gradient(90deg, #4b6cb7, #182848);
            color: white;
            box-shadow: 0 3px 10px rgba(75, 108, 183, 0.3);
        }
        .mode-settings {
            display: none;
            animation: fadeIn 0.5s;
        }
        .mode-settings.active {
            display: block;
        }
        .help-text {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            padding: 20px;
            border-radius: 15px;
            margin: 25px 0;
            font-size: 1em;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #bbdefb;
        }
        .help-text h4 {
            margin-top: 0;
            color: #2c3e50;
            font-size: 1.3em;
        }
        .word-list {
            max-height: 220px;
            overflow-y: auto;
            border: 2px solid #ddd;
            border-radius: 12px;
            padding: 15px;
            margin-top: 20px;
            background: white;
            box-shadow: inset 0 2px 5px rgba(0,0,0,0.05);
        }
        .word-item {
            padding: 12px;
            border-bottom: 1px solid #eee;
            display: flex;
            transition: background 0.2s;
        }
        .word-item:hover {
            background: #f5f9ff;
        }
        .word-item:last-child {
            border-bottom: none;
        }
        .word-item .word-text {
            flex: 1;
            font-weight: 700;
            color: #4b6cb7;
        }
        .word-item .meaning-text {
            flex: 2;
            color: #666;
        }
        .file-type-selector {
            display: flex;
            margin: 20px 0;
            background: #e9ecef;
            border-radius: 30px;
            overflow: hidden;
            box-shadow: inset 0 2px 5px rgba(0,0,0,0.1);
        }
        .file-type-btn {
            flex: 1;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
        }
        .file-type-btn:hover {
            background-color: #d1d1d1;
        }
        .file-type-btn.active {
            background: linear-gradient(90deg, #4b6cb7, #182848);
            color: white;
            box-shadow: 0 3px 10px rgba(75, 108, 183, 0.3);
        }
        .tab-content {
            display: none;
            animation: fadeIn 0.5s;
        }
        .tab-content.active {
            display: block;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }
            .upload-section, .dictation-section, .settings-section {
                min-width: 100%;
            }
            .upload-section, .settings-section {
                border-right: none;
                border-left: none;
                border-top: 1px solid #d1dfff;
                border-bottom: 1px solid #d1dfff;
            }
            .word {
                font-size: 3em;
            }
            .meaning {
                font-size: 1.5em;
            }
            .control-btn {
                width: 70px;
                height: 70px;
                font-size: 1.5em;
            }
            h1 {
                font-size: 2.2em;
            }
        }
    </style>
</head>
<body>
    <!-- Main container for the entire application -->
    <div class="container">
        <!-- Header section with title -->
        <header>
            <h1>英语单词听写工具</h1>
            <p class="subtitle">提升英语听力和拼写能力的好帮手</p>
        </header>
        <!-- Main content area with three sections -->
        <div class="main-content">
            <!-- Left section: Vocabulary import -->
            <div class="upload-section">
                <h2 class="section-title">词库导入</h2>
                <!-- Help instructions for file formats -->
                <div class="help-text">
                    <h4>使用说明</h4>
                    <p><strong>CSV格式：</strong>英语单词,中文意思</p>
                    <p>例如：apple,苹果</p>
                    <br>
                    <p><strong>TXT格式：</strong>支持一个单词多个含义</p>
                    <p>格式：单词 [含义1;含义2;含义3]</p>
                    <p>例如：apple [苹果;苹果树;苹果公司]</p>
                </div>
                <!-- File type selector (CSV/TXT) -->
                <div class="file-type-selector">
                    <div class="file-type-btn active" data-type="csv" onclick="switchFileType('csv')">CSV文件</div>
                    <div class="file-type-btn" data-type="txt" onclick="switchFileType('txt')">TXT文件</div>
                </div>
                <!-- File upload tabs -->
                <div class="tab-content active" id="csvTab">
                    <div class="upload-area" onclick="document.getElementById('csvFile').click()" 
                         ondrop="handleFileDrop(event, 'csv')" ondragover="event.preventDefault()">
                        <div class="upload-icon">📁</div>
                        <h3>上传CSV词库文件</h3>
                        <p>点击选择或拖拽文件到此处</p>
                    </div>
                    <input type="file" id="csvFile" accept=".csv" style="display: none;">
                </div>
                <div class="tab-content" id="txtTab">
                    <div class="upload-area" onclick="document.getElementById('txtFile').click()"
                         ondrop="handleFileDrop(event, 'txt')" ondragover="event.preventDefault()">
                        <div class="upload-icon">📄</div>
                        <h3>上传TXT词库文件</h3>
                        <p>点击选择或拖拽文件到此处</p>
                    </div>
                    <input type="file" id="txtFile" accept=".txt" style="display: none;">
                </div>
                <!-- Sample vocabulary button -->
                <div class="file-inputs">
                    <div class="file-input">
                        <label>示例词库：</label>
                        <button class="btn btn-secondary btn-block" onclick="loadSampleWords()">加载示例词库</button>
                    </div>
                </div>
                <!-- Display area for loaded vocabulary -->
                <div class="word-list" id="wordList">
                    <div class="word-item">请先上传词库文件</div>
                </div>
                <!-- Control buttons -->
                <div style="margin-top: 25px; text-align: center;">
                    <button class="btn btn-success btn-lg" onclick="startDictation()">开始听写</button>
                    <button class="btn btn-warning" onclick="resetDictation()">重置</button>
                </div>
            </div>
            <!-- Middle section: Dictation area -->
            <div class="dictation-section">
                <h2 class="section-title">听写区域</h2>
                <!-- Mode selector (Dictation/Repeat) -->
                <div class="mode-toggle">
                    <div class="mode-btn active" data-mode="dictation" onclick="switchMode('dictation')">听写模式</div>
                    <div class="mode-btn" data-mode="repeat" onclick="switchMode('repeat')">跟读模式</div>
                </div>
                <!-- Word display area -->
                <div class="word-display">
                    <div class="word" id="currentWord">-</div>
                    <div class="meaning" id="currentMeaning">请先加载词库</div>
                </div>
                <!-- Playback controls -->
                <div class="controls">
                    <button class="btn control-btn" onclick="prevWord()" title="上一个">⬅️</button>
                    <!-- 按钮图标和标题会在JS中动态更新 -->
                    <button class="btn control-btn btn-warning" onclick="togglePlayPause()" title="播放" id="playPauseBtn">▶️</button>
                    <button class="btn control-btn btn-danger" onclick="stopWord()" title="停止">⏹️</button>
                    <button class="btn control-btn" onclick="nextWord()" title="下一个">➡️</button>
                </div>
                <!-- Progress indicator -->
                <div class="progress-container">
                    <div class="progress-bar" id="progressBar" style="width: 0%"></div>
                </div>
                <div class="progress-text" id="progressText">0 / 0</div>
            </div>
            <!-- Right section: Settings -->
            <div class="settings-section">
                <h2 class="section-title">设置</h2>
                <!-- General settings -->
                <div class="setting-group">
                    <h3>通用配置</h3>
                    <div class="setting-item">
                        <label for="volume">音量: <span id="volumeValue">100</span>%</label>
                        <input type="range" id="volume" min="0" max="1" step="0.1" value="1" oninput="updateVolumeValue()">
                    </div>
                    <div class="setting-item">
                        <label for="rate">语速: <span id="rateValue">1.0</span>x</label>
                        <input type="range" id="rate" min="0.5" max="2" step="0.1" value="1" oninput="updateRateValue()">
                    </div>
                    <div class="setting-item">
                        <label for="voice">音色</label>
                        <select id="voice">
                            <option value="Microsoft David - English (United States)">英语(美国) - 男声</option>
                            <option value="Microsoft Zira - English (United States)">英语(美国) - 女声</option>
                            <option value="Google US English">英语 - 标准</option>
                        </select>
                    </div>
                    <div class="setting-item">
                        <label>
                            <input type="checkbox" id="randomMode"> 随机播放
                        </label>
                    </div>
                </div>
                <!-- Mode-specific settings -->
                <div class="setting-group">
                    <h3>模式设置</h3>
                    <div class="mode-settings active" id="dictationSettings">
                        <h4>听写模式</h4>
                        <div class="setting-item">
                            <label>
                                <input type="checkbox" id="showMeaning" checked> 显示中文意思
                            </label>
                        </div>
                        <div class="setting-item">
                            <label>
                                <input type="checkbox" id="autoPlay" checked> 自动播放下一个
                            </label>
                        </div>
                        <div class="setting-item">
                            <label for="interval">播放间隔(秒)</label>
                            <input type="number" id="interval" min="1" max="10" value="3">
                        </div>
                    </div>
                    <div class="mode-settings" id="repeatSettings">
                        <h4>跟读模式</h4>
                        <div class="setting-item">
                            <label>
                                <input type="checkbox" id="repeatWord" checked> 重复播放单词
                            </label>
                        </div>
                        <div class="setting-item">
                            <label for="repeatCount">重复次数</label>
                            <input type="number" id="repeatCount" min="1" max="10" value="2">
                        </div>
                        <div class="setting-item">
                            <label for="repeatDelay">重复间隔(秒)</label>
                            <input type="number" id="repeatDelay" min="1" max="5" value="2">
                        </div>
                    </div>
                </div>
                <!-- Quick actions -->
                <div class="setting-group">
                    <h3>快捷操作</h3>
                    <button class="btn btn-info btn-block" onclick="speakCurrentWord()">朗读当前单词</button>
                </div>
            </div>
        </div>
    </div>
    <script>
        // 全局变量
        let words = [];                         // 存储词汇列表
        let currentIndex = 0;                   // 当前词汇索引
        let isPlaying = false;                  // 播放状态标记
        let currentMode = 'dictation';          // 当前模式 (dictation 或 repeat)
        let currentFileType = 'csv';            // 当前文件类型 (csv 或 txt)
        let speechSynthesis = window.speechSynthesis || window.webkitSpeechSynthesis;
        let voices = [];                        // 可用语音列表
        let currentUtterance = null;            // 当前语音对象，用于暂停/恢复
        let isUserInteracted = false;           // 用户是否已与页面交互
        let voiceLoadAttempts = 0;              // 语音加载尝试次数
        let speechRetryCount = 0;               // 语音播放重试次数
        let maxSpeechRetries = 3;               // 最大重试次数
        let isSpeechPending = false;            // 是否有语音播放待处理
        // --- 新增变量用于处理暂停逻辑 ---
        let pausedWordIndex = -1;               // 记录暂停时的单词索引，-1表示未暂停

        // 检查浏览器是否支持语音合成
        const supportsSpeechSynthesis = 'speechSynthesis' in window || 'webkitSpeechSynthesis' in window;
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查浏览器兼容性
            checkBrowserCompatibility();
            // 添加用户交互事件监听器
            document.body.addEventListener('click', function() {
                isUserInteracted = true;
            }, {once: true});
            document.body.addEventListener('keydown', function() {
                isUserInteracted = true;
            }, {once: true});
            // 添加一个全局点击监听器，确保用户交互被检测到
            document.addEventListener('click', function() {
                isUserInteracted = true;
            }, {once: true});
            loadVoices();
            setupEventListeners();
            // 设置文件上传事件监听器
            document.getElementById('csvFile').addEventListener('change', function(event) {
                handleFileUpload(event, 'csv');
            });
            document.getElementById('txtFile').addEventListener('change', function(event) {
                handleFileUpload(event, 'txt');
            });
        });
        // 检查浏览器兼容性并提供相关信息
        function checkBrowserCompatibility() {
            const info = {
                supportsSpeechSynthesis: supportsSpeechSynthesis,
                userAgent: navigator.userAgent,
                platform: navigator.platform,
                language: navigator.language
            };
            console.log('浏览器兼容性信息:', info);
            // 检查是否为已知的有问题的浏览器/版本
            const userAgent = navigator.userAgent;
            // Chrome浏览器特殊处理
            if (userAgent.includes('Chrome') && !userAgent.includes('Edg')) {
                console.log('检测到Chrome浏览器，可能需要特殊处理');
            }
            // Edge浏览器
            if (userAgent.includes('Edg')) {
                console.log('检测到Edge浏览器');
            }
            // Firefox浏览器
            if (userAgent.includes('Firefox')) {
                console.log('检测到Firefox浏览器，可能需要特殊处理');
            }
            return info;
        }
        // 加载语音合成声音
        function loadVoices() {
            // Check if speech synthesis is supported
            if (!supportsSpeechSynthesis) {
                console.warn('浏览器不支持语音合成功能');
                return;
            }
            // 尝试获取语音列表
            try {
                voices = speechSynthesis.getVoices();
            } catch (e) {
                console.error('获取语音列表时出错:', e);
            }
            // 如果还没有声音，等待加载
            if (voices.length === 0) {
                voiceLoadAttempts++;
                // Handle both standard and WebKit events
                if (speechSynthesis.onvoiceschanged !== undefined) {
                    speechSynthesis.onvoiceschanged = function() {
                        voices = speechSynthesis.getVoices();
                        populateVoiceList();
                    };
                } else if (speechSynthesis.addEventListener) {
                    speechSynthesis.addEventListener('voiceschanged', function() {
                        voices = speechSynthesis.getVoices();
                        populateVoiceList();
                    });
                }
                // 如果多次尝试仍未加载到语音，则使用默认语音
                if (voiceLoadAttempts > 3) {
                    console.warn('无法加载语音列表，将使用默认语音');
                    populateVoiceList();
                } else {
                    // 继续尝试加载
                    setTimeout(function() {
                        loadVoices();
                    }, 500);
                }
            } else {
                populateVoiceList();
            }
        }
        // 填充语音选择列表
        function populateVoiceList() {
            const voiceSelect = document.getElementById('voice');
            if (!voiceSelect) return;
            voiceSelect.innerHTML = '';
            // 获取所有可用语音
            let availableVoices = [];
            try {
                availableVoices = speechSynthesis.getVoices();
            } catch (e) {
                console.error('获取语音列表时出错:', e);
            }
            // 优先选择英语语音
            const englishVoices = availableVoices.filter(voice => 
                voice.lang.includes('en') || voice.lang.includes('EN') || 
                voice.lang.includes('English') || voice.name.includes('English')
            );
            // 如果没有英语语音，则使用所有语音
            const voicesToUse = englishVoices.length > 0 ? englishVoices : availableVoices;
            if (voicesToUse.length === 0) {
                // 添加默认选项
                const option = document.createElement('option');
                option.value = 'default';
                option.textContent = '默认语音';
                voiceSelect.appendChild(option);
                return;
            }
            // 添加所有可用语音到选择列表
            voicesToUse.forEach((voice, index) => {
                const option = document.createElement('option');
                const voiceName = voice.name || voice.voiceURI || '未知语音';
                const voiceLang = voice.lang || '未知语言';
                option.value = voiceName;
                option.textContent = `${voiceName} (${voiceLang})`;
                voiceSelect.appendChild(option);
            });
            // 尝试选择一个合适的默认语音
            let defaultVoice = null;
            // 优先选择常见的英语语音
            const preferredVoices = [
                'Google US English',
                'Microsoft David Desktop - English (United States)',
                'Microsoft Zira Desktop - English (United States)',
                'English United States',
                'en-US'
            ];
            for (const preferredVoice of preferredVoices) {
                defaultVoice = voicesToUse.find(voice => 
                    voice.name.includes(preferredVoice) || voice.voiceURI.includes(preferredVoice)
                );
                if (defaultVoice) break;
            }
            // 如果没找到首选语音，则选择第一个英语语音
            if (!defaultVoice && englishVoices.length > 0) {
                defaultVoice = englishVoices[0];
            }
            // 如果仍然没有找到，则选择第一个可用语音
            if (!defaultVoice && voicesToUse.length > 0) {
                defaultVoice = voicesToUse[0];
            }
            // 设置默认值
            if (defaultVoice) {
                try {
                    voiceSelect.value = defaultVoice.name || defaultVoice.voiceURI;
                } catch (e) {
                    console.error('设置默认语音时出错:', e);
                }
            }
        }
        // 设置事件监听器
        function setupEventListeners() {
            // 音量控制
            const volumeControl = document.getElementById('volume');
            if (volumeControl) {
                volumeControl.addEventListener('input', function() {
                    updateVolumeValue();
                });
            }
            // 语速控制
            const rateControl = document.getElementById('rate');
            if (rateControl) {
                rateControl.addEventListener('input', function() {
                    updateRateValue();
                });
            }
        }
        // 更新音量显示值
        function updateVolumeValue() {
            const volumeControl = document.getElementById('volume');
            const volumeValue = document.getElementById('volumeValue');
            if (volumeControl && volumeValue) {
                const volume = volumeControl.value;
                volumeValue.textContent = Math.round(volume * 100);
            }
        }
        // 更新语速显示值
        function updateRateValue() {
            const rateControl = document.getElementById('rate');
            const rateValue = document.getElementById('rateValue');
            if (rateControl && rateValue) {
                const rate = rateControl.value;
                rateValue.textContent = rate;
            }
        }
        // 切换文件类型
        function switchFileType(type) {
            console.log('切换文件类型:', type);
            currentFileType = type;
            // 更新按钮状态
            document.querySelectorAll('.file-type-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            const activeBtn = document.querySelector(`.file-type-btn[data-type="${type}"]`);
            if (activeBtn) {
                activeBtn.classList.add('active');
            }
            // 显示对应内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            const activeTab = document.getElementById(`${type}Tab`);
            if (activeTab) {
                activeTab.classList.add('active');
            }
        }
        // 处理文件上传
        function handleFileUpload(event, fileType) {
            const file = event.target.files[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = function(e) {
                const content = e.target.result;
                if (fileType === 'csv') {
                    parseCSV(content);
                } else if (fileType === 'txt') {
                    parseTXT(content);
                }
            };
            reader.readAsText(file, 'UTF-8');
        }
        // 处理拖拽文件
        function handleFileDrop(event, fileType) {
            event.preventDefault();
            const file = event.dataTransfer.files[0];
            if (!file) return;
            // 检查文件类型
            if (fileType === 'csv' && !file.name.endsWith('.csv')) {
                alert('请选择CSV文件');
                return;
            } else if (fileType === 'txt' && !file.name.endsWith('.txt')) {
                alert('请选择TXT文件');
                return;
            }
            const reader = new FileReader();
            reader.onload = function(e) {
                const content = e.target.result;
                if (fileType === 'csv') {
                    parseCSV(content);
                } else if (fileType === 'txt') {
                    parseTXT(content);
                }
            };
            reader.readAsText(file, 'UTF-8');
        }
        // 解析CSV内容
        function parseCSV(content) {
            words = [];
            const lines = content.split('\n');
            lines.forEach(line => {
                line = line.trim();
                if (line) {
                    const parts = line.split(',');
                    if (parts.length >= 2) {
                        words.push({
                            word: parts[0].trim(),
                            meaning: parts[1].trim()
                        });
                    }
                }
            });
            updateWordList();
            resetDictation();
        }
        // 解析TXT内容（支持一个单词多个含义）
        function parseTXT(content) {
            words = [];
            const lines = content.split('\n');
            lines.forEach(line => {
                line = line.trim();
                if (line) {
                    // 匹配格式：word [meaning1;meaning2;meaning3]
                    const match = line.match(/^([^[]+)\s*$(.*?)$/);
                    if (match) {
                        const word = match[1].trim();
                        const meanings = match[2].split(';').map(m => m.trim()).join('; ');
                        words.push({
                            word: word,
                            meaning: meanings
                        });
                    } else {
                        // 如果不匹配特殊格式，则按普通文本处理
                        const parts = line.split(' ');
                        if (parts.length >= 2) {
                            words.push({
                                word: parts[0].trim(),
                                meaning: parts.slice(1).join(' ').trim()
                            });
                        }
                    }
                }
            });
            updateWordList();
            resetDictation();
        }
        // 更新词库列表显示
        function updateWordList() {
            const wordList = document.getElementById('wordList');
            if (!wordList) return;
            wordList.innerHTML = '';
            if (words.length === 0) {
                wordList.innerHTML = '<div class="word-item">暂无词汇</div>';
                return;
            }
            words.forEach((item, index) => {
                const wordItem = document.createElement('div');
                wordItem.className = 'word-item';
                wordItem.innerHTML = `
                    <div class="word-text">${item.word}</div>
                    <div class="meaning-text">${item.meaning}</div>
                `;
                wordList.appendChild(wordItem);
            });
        }
        // 加载示例词库
        function loadSampleWords() {
            console.log('加载示例词库，当前文件类型:', currentFileType);
            // 根据当前文件类型加载对应的示例词库
            if (currentFileType === 'csv') {
                const sampleContent = `apple,苹果
book,书
computer,电脑
water,水
house,房子
car,汽车
school,学校
teacher,老师
student,学生
english,英语
chinese,中文
music,音乐
sport,运动
food,食物
friend,朋友
family,家庭
happy,快乐
beautiful,美丽的
difficult,困难的
important,重要的`;
                parseCSV(sampleContent);
            } else {
                const sampleContent = `apple [苹果;苹果树;苹果公司]
book [书;书籍;预定]
computer [电脑;计算机]
water [水;水域;海域]
house [房子;住宅;议院]
car [汽车;轿车;车厢]
school [学校;学院;学派]
teacher [老师;教师;导师]
student [学生;学者;研究人员]
english [英语;英文]
chinese [中文;中国的;中国人]
music [音乐;乐曲]
sport [运动;体育]
food [食物;食品]
friend [朋友;赞助人]
family [家庭;家族;亲属]
happy [快乐;高兴;乐意]
beautiful [美丽的;漂亮的;美好的]
difficult [困难的;艰难的;复杂的]
important [重要的;重大的;有势力的]`;
                parseTXT(sampleContent);
            }
        }
        // 切换模式
        function switchMode(mode) {
            currentMode = mode;
            // 更新按钮状态
            document.querySelectorAll('.mode-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            const activeModeBtn = document.querySelector(`.mode-btn[data-mode="${mode}"]`);
            if (activeModeBtn) {
                activeModeBtn.classList.add('active');
            }
            // 显示对应设置
            document.querySelectorAll('.mode-settings').forEach(setting => {
                setting.classList.remove('active');
            });
            const activeModeSettings = document.getElementById(`${mode}Settings`);
            if (activeModeSettings) {
                activeModeSettings.classList.add('active');
            }
        }
        // 开始听写
        function startDictation() {
            if (words.length === 0) {
                alert('请先加载词库！');
                return;
            }
            console.log('开始听写，词汇数量:', words.length);
            currentIndex = 0;
            isPlaying = false;
            // --- 重置暂停状态 ---
            pausedWordIndex = -1;
            updateDisplay();
            updateProgress();
            playWord();
        }
        // 重置听写
        function resetDictation() {
            currentIndex = 0;
            isPlaying = false;
            // --- 重置暂停状态 ---
            pausedWordIndex = -1;
            updateDisplay();
            updateProgress();
            // 停止任何正在进行的播放
            if (supportsSpeechSynthesis) {
                speechSynthesis.cancel();
            }
            // 重置暂停按钮状态
            updatePlayPauseButton(true); // 重置为播放图标
        }
        // 更新显示
        function updateDisplay() {
            const wordElement = document.getElementById('currentWord');
            const meaningElement = document.getElementById('currentMeaning');
            if (words.length === 0) {
                if (wordElement) wordElement.textContent = '-';
                if (meaningElement) meaningElement.textContent = '请先加载词库';
                return;
            }
            const currentWord = words[currentIndex];
            if (wordElement) wordElement.textContent = currentWord.word;
            // 根据设置决定是否显示中文意思
            const showMeaningCheckbox = document.getElementById('showMeaning');
            if (meaningElement) {
                const showMeaning = showMeaningCheckbox ? showMeaningCheckbox.checked : true;
                meaningElement.textContent = showMeaning ? currentWord.meaning : '...';
            }
        }
        // 更新进度
        function updateProgress() {
            const progressText = document.getElementById('progressText');
            const progressBar = document.getElementById('progressBar');
            if (words.length === 0) {
                if (progressText) progressText.textContent = '0 / 0';
                if (progressBar) progressBar.style.width = '0%';
                return;
            }
            const progress = ((currentIndex + 1) / words.length) * 100;
            if (progressBar) progressBar.style.width = progress + '%';
            if (progressText) progressText.textContent = `${currentIndex + 1} / ${words.length}`;
        }
        // 播放单词
        function playWord() {
            if (words.length === 0) {
                console.warn('词汇列表为空，无法播放');
                return;
            }
            const currentWord = words[currentIndex];
            console.log('播放单词:', currentWord.word);
            speak(currentWord.word);
            isPlaying = true;
            // --- 开始播放时清除暂停状态 ---
            pausedWordIndex = -1;
            // 更新按钮显示为暂停图标
            updatePlayPauseButton(false);
        }
        
        // --- 新增或修改的函数：更新播放/暂停按钮状态 ---
        function updatePlayPauseButton(isPlayState) {
             const playPauseBtn = document.getElementById('playPauseBtn');
             if (playPauseBtn) {
                 if (isPlayState) {
                     playPauseBtn.innerHTML = '▶️';
                     playPauseBtn.title = '播放';
                 } else {
                     playPauseBtn.innerHTML = '⏸️';
                     playPauseBtn.title = '暂停';
                 }
             }
        }

        // --- 核心修改：统一的播放/暂停控制函数 ---
        function togglePlayPause() {
            if (!supportsSpeechSynthesis) return;

            // 如果正在播放，则执行“暂停”逻辑：停止播放并记录位置
            if (isPlaying) {
                speechSynthesis.cancel(); // 立即停止
                isPlaying = false;
                pausedWordIndex = currentIndex; // 记录当前单词索引
                console.log('语音已暂停，记录单词索引:', pausedWordIndex);
                updatePlayPauseButton(true); // 更新按钮为播放图标
            }
            // 如果未在播放（停止或已暂停），则执行“播放”逻辑
            else {
                // 如果有记录的暂停位置，则从该位置恢复播放
                if (pausedWordIndex !== -1) {
                    console.log('从暂停位置恢复播放，单词索引:', pausedWordIndex);
                    currentIndex = pausedWordIndex; // 恢复索引
                    updateDisplay(); // 更新UI显示
                    playWord(); // 播放记录的单词
                    // 播放开始后，可以考虑清除记录，或者保留以便再次暂停后恢复。
                    // 这里选择保留，允许多次暂停/恢复同一个单词。
                    // pausedWordIndex = -1; // 如果希望恢复播放后立即清除记录，取消注释此行
                }
                // 如果没有记录的暂停位置（初始播放或停止后播放），则播放当前单词
                else {
                    console.log('开始播放当前单词');
                    playWord();
                }
            }
        }

        // 停止播放
        function stopWord() {
            if (!supportsSpeechSynthesis) return;
            speechSynthesis.cancel();
            isPlaying = false;
            // --- 停止时也清除暂停状态 ---
            pausedWordIndex = -1;
            // 重置按钮显示为播放图标
            updatePlayPauseButton(true);
            console.log('语音已停止');
        }
        // 上一个单词
        function prevWord() {
            if (words.length === 0) return;
            currentIndex = (currentIndex - 1 + words.length) % words.length;
            updateDisplay();
            updateProgress();
            // --- 切换单词时清除暂停状态 ---
            pausedWordIndex = -1;
            // 如果之前正在播放，则继续播放新单词
            if (isPlaying) { // 注意：暂停状态时 isPlaying 是 false，所以不会触发
                // 先停止当前播放
                stopWord();
                // 然后播放新单词
                playWord();
            } else {
                 // 如果之前是暂停状态，现在切换了单词，应该更新按钮状态为可播放
                 updatePlayPauseButton(true);
            }
        }
        // 下一个单词
        function nextWord() {
            if (words.length === 0) return;
            // 根据是否随机播放决定下一个单词
            const randomModeCheckbox = document.getElementById('randomMode');
            const randomMode = randomModeCheckbox ? randomModeCheckbox.checked : false;
            if (randomMode) {
                currentIndex = Math.floor(Math.random() * words.length);
            } else {
                currentIndex = (currentIndex + 1) % words.length;
            }
            updateDisplay();
            updateProgress();
            // --- 切换单词时清除暂停状态 ---
            pausedWordIndex = -1;
            // 如果之前正在播放，则继续播放新单词
            if (isPlaying) { // 注意：暂停状态时 isPlaying 是 false，所以不会触发
                // 先停止当前播放
                stopWord();
                // 然后播放新单词
                playWord();
            } else {
                 // 如果之前是暂停状态，现在切换了单词，应该更新按钮状态为可播放
                 updatePlayPauseButton(true);
            }
            // 如果启用了自动播放，则播放新单词
            // 注意：自动播放逻辑在 speak 的 onend 回调中处理，那里也需要检查 isPlaying 状态
        }
        // 语音合成
        function speak(text) {
            console.log('尝试播放语音:', text);
            // 检查是否已经有语音在待播放
            if (isSpeechPending) {
                console.log('有语音正在待播放，取消当前请求');
                return;
            }
            isSpeechPending = true;
            // Check if speech synthesis is supported
            if (!supportsSpeechSynthesis) {
                console.warn('浏览器不支持speechSynthesis API');
                alert('您的浏览器不支持语音合成功能，将使用视觉提示代替');
                playAudioFallback(text);
                isSpeechPending = false;
                return;
            }
            // 检查用户是否已与页面交互（浏览器安全策略要求）
            if (!isUserInteracted) {
                console.warn('用户未与页面交互，无法播放语音');
                alert('请先点击页面任意位置或按键后再播放语音');
                playAudioFallback(text); // 使用降级方案
                isSpeechPending = false;
                return;
            }
            // 重试机制
            function attemptSpeak(retryCount) {
                console.log(`第${retryCount + 1}次尝试播放语音`);
                // 先取消当前播放
                try {
                    speechSynthesis.cancel();
                    console.log('已取消当前播放');
                } catch (e) {
                    console.error('取消当前播放时出错:', e);
                }
                // 创建语音对象
                let utterance;
                try {
                    utterance = new SpeechSynthesisUtterance(text);
                    console.log('成功创建语音对象');
                } catch (e) {
                    console.error('创建SpeechSynthesisUtterance时出错:', e);
                    if (retryCount < maxSpeechRetries) {
                        console.log(`创建语音对象失败，${1000 * (retryCount + 1)}ms后重试...`);
                        setTimeout(() => attemptSpeak(retryCount + 1), 1000 * (retryCount + 1));
                        return;
                    } else {
                        alert('创建语音对象失败，将使用视觉提示代替');
                        playAudioFallback(text); // 使用降级方案
                        isSpeechPending = false;
                        isPlaying = false;
                        // isPaused = false; // 不再需要 isPaused
                        updatePlayPauseButton(true); // 更新按钮状态
                        return;
                    }
                }
                currentUtterance = utterance; // Track the current utterance
                // 设置参数
                try {
                    const volumeControl = document.getElementById('volume');
                    const rateControl = document.getElementById('rate');
                    const volume = volumeControl ? parseFloat(volumeControl.value) || 1 : 1;
                    const rate = rateControl ? parseFloat(rateControl.value) || 1 : 1;
                    utterance.volume = volume;
                    utterance.rate = rate;
                    console.log('设置语音参数 - 音量:', volume, '语速:', rate);
                } catch (e) {
                    console.warn('设置语音参数时出错，使用默认值:', e);
                    utterance.volume = 1;
                    utterance.rate = 1;
                }
                // 设置音色
                try {
                    const voiceControl = document.getElementById('voice');
                    const voiceName = voiceControl ? voiceControl.value : null;
                    console.log('尝试设置语音:', voiceName);
                    if (voiceName && voiceName !== 'default') {
                        // 尝试找到匹配的语音
                        let selectedVoice = null;
                        try {
                            const availableVoices = speechSynthesis.getVoices();
                            console.log('可用语音列表:', availableVoices.map(v => v.name));
                            selectedVoice = availableVoices.find(voice => 
                                voice.name === voiceName || voice.voiceURI === voiceName
                            );
                            if (selectedVoice) {
                                utterance.voice = selectedVoice;
                                console.log('成功设置语音:', selectedVoice.name);
                            } else {
                                console.warn('未找到指定语音:', voiceName);
                            }
                        } catch (e) {
                            console.warn('获取语音列表时出错:', e);
                        }
                    } else {
                        console.log('使用默认语音');
                    }
                } catch (e) {
                    console.warn('设置语音时出错:', e);
                }
                // 添加事件监听器
                utterance.onstart = function() {
                    console.log('语音播放开始:', text);
                    isPlaying = true;
                    // isPaused = false; // 不再需要 isPaused
                    isSpeechPending = false;
                    speechRetryCount = 0; // 重置重试计数
                    updatePlayPauseButton(false); // 更新按钮为暂停图标
                };
                utterance.onerror = function(event) {
                    console.error('语音播放出错:', event);
                    console.error('错误详情:', event.error);
                    // 如果是interrupted错误且还有重试次数，则重试
                    if (event.error === 'interrupted' && retryCount < maxSpeechRetries) {
                        console.log(`语音播放被中断，${1000 * (retryCount + 1)}ms后重试...`);
                        setTimeout(() => attemptSpeak(retryCount + 1), 1000 * (retryCount + 1));
                        return;
                    }
                    // 如果是network错误且还有重试次数，则重试
                    else if (event.error === 'network' && retryCount < maxSpeechRetries) {
                        console.log(`网络错误导致语音播放失败，${1500 * (retryCount + 1)}ms后重试...`);
                        setTimeout(() => attemptSpeak(retryCount + 1), 1500 * (retryCount + 1));
                        return;
                    }
                    // 其他错误或重试次数已用完
                    else {
                        const errorMsg = event.error || '未知错误';
                        console.error(`语音播放失败(${errorMsg})，重试${retryCount}次后仍然失败`);
                        alert(`语音播放失败(${errorMsg})，将使用视觉提示代替`);
                        playAudioFallback(text); // 使用降级方案
                        isSpeechPending = false;
                        isPlaying = false;
                        // isPaused = false; // 不再需要 isPaused
                        updatePlayPauseButton(true); // 更新按钮状态
                    }
                };
                // 播放完成后的处理
                utterance.onend = function() {
                    console.log('语音播放结束:', text);
                    isPlaying = false;
                    // isPaused = false; // 不再需要 isPaused
                    isSpeechPending = false;
                    speechRetryCount = 0; // 重置重试计数
                    updatePlayPauseButton(true); // 更新按钮为播放图标
                    // 听写模式下自动播放下一个
                    const autoPlayCheckbox = document.getElementById('autoPlay');
                    // --- 关键修改：自动播放前检查是否仍处于播放状态 ---
                    if (currentMode === 'dictation' && autoPlayCheckbox && autoPlayCheckbox.checked && isPlaying) {
                        try {
                            const intervalControl = document.getElementById('interval');
                            const interval = intervalControl ? parseInt(intervalControl.value) * 1000 : 3000;
                            console.log('设置自动播放下一个单词，延迟:', interval, 'ms');
                            setTimeout(() => {
                                // --- 再次检查状态，防止在延迟期间被暂停或停止 ---
                                const autoPlayCheckbox = document.getElementById('autoPlay');
                                if (autoPlayCheckbox && autoPlayCheckbox.checked && isPlaying) {
                                    nextWord();
                                }
                            }, interval);
                        } catch (e) {
                            console.error('自动播放下一个单词时出错:', e);
                        }
                    }
                    // 跟读模式下重复播放
                    const repeatWordCheckbox = document.getElementById('repeatWord');
                    if (currentMode === 'repeat' && repeatWordCheckbox && repeatWordCheckbox.checked) {
                        try {
                            const repeatCountControl = document.getElementById('repeatCount');
                            const repeatDelayControl = document.getElementById('repeatDelay');
                            const repeatCount = repeatCountControl ? parseInt(repeatCountControl.value) : 2;
                            const repeatDelay = repeatDelayControl ? parseInt(repeatDelayControl.value) * 1000 : 2000;
                            console.log('跟读模式，重复次数:', repeatCount, '延迟:', repeatDelay);
                            // --- 简单实现：重新播放当前单词 ---
                            // 注意：这里的实现可能需要根据具体需求调整
                            if (repeatCount > 1) {
                                let count = 1;
                                const repeatInterval = setInterval(() => {
                                    if (count < repeatCount && isPlaying) { // 检查 isPlaying
                                        speak(text);
                                        count++;
                                    } else {
                                        clearInterval(repeatInterval);
                                    }
                                }, repeatDelay);
                            }
                        } catch (e) {
                            console.error('跟读模式处理时出错:', e);
                        }
                    }
                };
                // 开始播放
                try {
                    console.log('调用speechSynthesis.speak()');
                    speechSynthesis.speak(utterance);
                    console.log('已调用播放语音:', text);
                } catch (e) {
                    console.error('调用speak方法时出错:', e);
                    if (retryCount < maxSpeechRetries) {
                        console.log(`调用speak方法失败，${1000 * (retryCount + 1)}ms后重试...`);
                        setTimeout(() => attemptSpeak(retryCount + 1), 1000 * (retryCount + 1));
                        return;
                    } else {
                        alert('语音播放失败，将使用视觉提示代替');
                        playAudioFallback(text); // 使用降级方案
                        isSpeechPending = false;
                        isPlaying = false;
                        // isPaused = false; // 不再需要 isPaused
                        updatePlayPauseButton(true); // 更新按钮状态
                    }
                }
            }
            // 开始第一次尝试
            attemptSpeak(0);
        }
        // 添加一个简单的音频提示功能作为降级方案
        function playAudioFallback(text) {
            console.log('使用音频降级方案播放:', text);
            // 创建一个提示信息，告知用户当前播放的单词
            const notification = document.createElement('div');
            notification.style.position = 'fixed';
            notification.style.top = '20px';
            notification.style.right = '20px';
            notification.style.backgroundColor = '#4b6cb7';
            notification.style.color = 'white';
            notification.style.padding = '15px 20px';
            notification.style.borderRadius = '10px';
            notification.style.zIndex = '9999';
            notification.style.boxShadow = '0 4px 12px rgba(0,0,0,0.2)';
            notification.textContent = `播放单词: ${text}`;
            document.body.appendChild(notification);
            // 3秒后自动移除提示
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 3000);
        }
        // 检查浏览器是否支持特定的语音
        function checkVoiceSupport() {
            if (!supportsSpeechSynthesis) return false;
            try {
                const voices = speechSynthesis.getVoices();
                return voices.length > 0;
            } catch (e) {
                console.error('检查语音支持时出错:', e);
                return false;
            }
        }
        // 朗读当前单词
        function speakCurrentWord() {
            if (words.length === 0) return;
            const currentWord = words[currentIndex];
            speak(currentWord.word);
        }
    </script>
</body>
</html>